<template>
    <div class="bgColorF" :style="{ height: pcHeight }">
        <div class="flex-row mgL10">
            <div
                class="mgR20 w360 pd10 overflow-y boxShadow"
                :style="{ height: pcHeight2 }"
            >
                <el-input
                    v-model="filterText"
                    placeholder="输入文件夹名称查询"
                    clearable
                />
                <div>
                    <el-tree
                        ref="treeRef"
                        node-key="id"
                        class="filter-tree mgT15"
                        :data="folderData"
                        :props="defaultProps"
                        default-expand-all
                        icon="CaretRight"
                        :filter-node-method="filterNode"
                        :empty-text="loadingDataMsg"
                        :highlight-current="treeHighlightCurrent"
                        :expand-on-click-node="false"
                        :draggable="true"
                        @node-click="btnCheckNode"
                        @node-drag-end="handleDragEnd"
                    >
                        <template #default="{ node, data }">
                            <span class="custom-tree-node">
                                <span class="line-clamp2" :title="node.label">
                                    {{ data.label }}
                                </span>
                            </span>
                        </template>
                    </el-tree>
                </div>
            </div>
            <div :style="{ width: pcWidth }">
                <div class="h30 lh30">
                    <el-row :gutter="20" class="border_line_ddd">
                        <el-col :span="16" class="">
                            <el-breadcrumb separator="/">
                                <el-breadcrumb-item class="lh30">
                                    <el-button
                                        size="small"
                                        class="w26 cursor"
                                        text
                                        title="查看所有文件"
                                        @click="btnViewAllFile"
                                        style="margin-top: -3px"
                                    >
                                        <el-icon :size="22">
                                            <Folder />
                                        </el-icon>
                                    </el-button>
                                    文件路径：
                                </el-breadcrumb-item>
                                <el-breadcrumb-item
                                    v-for="(item, index) in breadTreeList"
                                    :key="index"
                                    class="line-clamp lh30"
                                >
                                    {{ item }}
                                </el-breadcrumb-item>
                            </el-breadcrumb>
                        </el-col>
                        <el-col :span="8" class="textR">
                            <el-button
                                type="primary"
                                size="small"
                                class="w26 pdL30 pdR30 mgR10"
                                title="确认选择所选文件"
                                v-if="props.chooseFileType == 2 && total > 0"
                                @click="btnGetAllChooseFile"
                            >
                                确认
                            </el-button>
                            <el-button
                                size="small"
                                class="w26 mgR10"
                                text
                                title="上传文件"
                                @click="btnUploadFile"
                            >
                                <el-icon :size="26">
                                    <UploadFilled />
                                </el-icon>
                            </el-button>
                        </el-col>
                    </el-row>
                </div>
                <div
                    class="overflow-y mgT20 mgB5"
                    :style="{ height: pcHeight3 }"
                >
                    <div v-if="total > 0">
                        <el-checkbox-group v-model="multipleSelection">
                            <el-card
                                shadow="hover"
                                class="inline-block w200 h165 mgR15 mgB10"
                                v-for="(item, index) in tableData"
                                :key="item"
                            >
                                <template #header>
                                    <el-button
                                        size="small"
                                        class="w26 mgL10"
                                        text
                                        title="选择此文件"
                                        @click="
                                            getFilePath(item.id, item.file_path)
                                        "
                                        v-if="chooseFileType == 1"
                                    >
                                        选择
                                    </el-button>
                                    <el-checkbox
                                        class="w26 mgL10"
                                        :value="item.id"
                                        v-else-if="chooseFileType == 2"
                                    >
                                        选择
                                    </el-checkbox>
                                </template>
                                <div style="">
                                    <el-image
                                        :src="require('@/assets/logo.png')"
                                        loading="lazy"
                                        fit="fill"
                                        style="width: 100px; height: 100px"
                                        class="cursor mgL45"
                                        @click="openFile(item)"
                                        v-if="
                                            item.file_suffix != 'jpg' &&
                                            item.file_suffix != 'png' &&
                                            item.file_suffix != 'gif'
                                        "
                                    />
                                    <el-image
                                        :src="
                                            item.file_path_compress
                                                ? item.file_path_compress
                                                : item.file_path
                                        "
                                        loading="lazy"
                                        fit="fill"
                                        style="width: 100%; height: 100px"
                                        class="cursor"
                                        preview-teleported
                                        :preview-src-list="previewSrcList"
                                        :initial-index="index"
                                        v-else
                                    />
                                </div>
                                <div
                                    class="textC h30 line-clamp"
                                    :title="item.file_old_name"
                                >
                                    {{ item.file_old_name }}
                                </div>
                            </el-card>
                        </el-checkbox-group>
                    </div>
                    <div class="mgT30 textC" v-else>
                        <span class="color9">{{ loadingDataMsg2 }}</span>
                    </div>
                </div>
            </div>
        </div>
        <el-drawer
            :close-on-press-escape="false"
            :close-on-click-modal="false"
            v-model="uploadDrawerFlag"
            :title="drawerTitle"
            size="70%"
        >
            <uploads
                @btnUploadDrawer="checkUploadDrawerFlag"
                @btnUpdateList="checkUpdateList"
                :fileTypeID="fileTypeID"
                :folder_name="tmpFolderName"
                :extractTreeData="extractTreeData"
            ></uploads>
        </el-drawer>
    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted, watch, getCurrentInstance } from "vue";
import type { FormInstance } from "element-plus";
import { ElMessage } from "element-plus";
import { getLocal } from "@/store/funcs";

import uploads from "@/views/user/fileUpload.vue";

import user from "@/store/api/user";

const props = defineProps({
    chooseFileType: {
        type: Number,
        default: 0,
    },
    chooseFileLocation: {
        type: Number,
        default: 0,
    },
    chooseFieldID: {
        type: String,
        default: "",
    },
});

const emits = defineEmits(["btnChooseFile"]);

const { proxy } = getCurrentInstance() as any;
const userInfo: any = ref({});

const pcHeight = ref(document.body.clientHeight - 60 + "px");
const pcHeight2 = ref(document.body.clientHeight - 80 + "px");
const pcHeight3 = ref(document.body.clientHeight - 145 + "px");
const pcWidth = ref(document.body.clientWidth - 600 + "px");
const treeRef: any = ref<FormInstance>() as any;
const filterText = ref("");
const folderData = ref([]);
const defaultProps = ref({
    children: "children",
    label: "label",
});
const loadingDataMsg = ref("数据加载中...");
const treeHighlightCurrent = ref(true);
const previewSrcList: any = ref([]);
const breadTreeList: any = ref([]);
const extractTreeData: any = ref([]);
const fileTypeID = ref("");
const treeFileTypeIDs: any = ref([]);
const tmpFolderName = ref("");
const uploadDrawerFlag = ref(false);
const drawerTitle = ref("上传文件");
const loadingDataMsg2 = ref("数据加载中...");
const total = ref(0);
const currentPage = ref(1); //当前第几页
const pageNum = ref(process.env.pageNum || 30); //每页条数
type tmpTableDataField = {
    id: string;
    file_path: string;
    file_path_compress: string;
    file_suffix: string;
    file_old_name: string;
    file_name: string;
};
const tableData = ref<tmpTableDataField[]>([]);
const multipleSelection = ref([]);

const checkFileSuffix: any = ref([]);

watch([filterText], ([filterTextNew], [filterTextOld]) => {
    if (filterTextNew !== filterTextOld) {
        treeRef.value.filter(filterTextNew);
    }
});

onMounted(() => {
    const myLocalData = getLocal("myLocalData");
    if (myLocalData && myLocalData.account) {
        userInfo.value = myLocalData;
        getFolderList();
    } else {
        proxy.$funcs.openPage("/login");
    }
});

const getFolderList = async () => {
    loadingDataMsg.value = "数据加载中...";
    const obj = {
        account: userInfo.value.account,
        type: "1",
        op: "1",
    };
    const tmpResult: any = await user.apiUserFile(obj);
    console.log("getFolderList tmpResult", tmpResult);
    if (tmpResult.code === 1) {
        folderData.value = tmpResult.data.count > 0 ? tmpResult.data.list : [];
        loadingDataMsg.value = tmpResult.data.count > 0 ? "" : "没有数据";
        getFileList();
    } else {
        ElMessage({
            type: "error",
            message: tmpResult.msg,
        });
        return false;
    }
};

const getFileList = async () => {
    const obj = {
        account: userInfo.value.account,
        type: 2,
        op: 1,
        type_id: treeFileTypeIDs.value,
        page: currentPage.value,
        pageNum: pageNum.value,
    };
    const tmpResult: any = await user.apiUserFile(obj);
    if (tmpResult.code === 1) {
        total.value = tmpResult.data.count;
        tableData.value = tmpResult.data.count ? tmpResult.data.list : [];
        tableData.value.forEach((item: any) => {
            if (item.file_path) {
                previewSrcList.value.push(item.file_path);
            }
        });
    } else {
        ElMessage({
            type: "error",
            message: tmpResult.msg,
        });
        return false;
    }
    loadingDataMsg2.value = total.value > 0 ? "" : "没有数据";
};

const filterNode = (value: any, data: any) => {
    if (!value) return true;
    return data.label.indexOf(value) !== -1;
};

//获取当前树节点和其父级节点
const getTreeNode = (node: any) => {
    if (node && node.label !== undefined) {
        breadTreeList.value.unshift(node.label); //在数组头部添加元素
        if (node["data"]["value"]) {
            extractTreeData.value.unshift(node["data"]["value"]);
        }
        getTreeNode(node.parent); //递归
    }
};

const getTreeChildrenIds = (groups: any, groupsIdName: any) => {
    //递归查询树当前节点及包含节点内容
    const { children } = groups;
    if (!Array.isArray(children) || !children.length) return false;
    children.forEach((item: any) => {
        const { value, label } = item;
        if (groupsIdName.indexOf({ value, label }) === -1) {
            groupsIdName.push({ value, label });
        }
        getTreeChildrenIds(item, groupsIdName);
    });

    return groupsIdName;
};

const btnCheckNode = (node: any, ev: any) => {
    fileTypeID.value = "";
    treeFileTypeIDs.value = [];
    tmpFolderName.value = "";
    breadTreeList.value = []; //初始化
    extractTreeData.value = [];
    if (ev) {
        getTreeNode(ev);
        fileTypeID.value = node.value;
        tmpFolderName.value = node.label;
        treeFileTypeIDs.value.push(node.value);

        if (node.children.length) {
            const tmpTypeIDs = getTreeChildrenIds(
                {
                    children: node.children,
                },
                []
            );

            if (Object.keys(tmpTypeIDs).length > 0) {
                tmpTypeIDs.forEach((item: any) => {
                    if (item.value) {
                        treeFileTypeIDs.value.push(item.value);
                    }
                });
            }
        }

        if (breadTreeList) {
            var tmpTitle = "";
            breadTreeList.value.forEach((item: any) => {
                tmpTitle += " / " + item;
            });
            drawerTitle.value = "上传文件：（路径：" + tmpTitle + "）";
        }

        treeHighlightCurrent.value = true;
        total.value = 0;
        tableData.value = [];
        previewSrcList.value = [];
        currentPage.value = 1;
        loadingDataMsg2.value = "数据载入中...";
        getFileList();
    }
};

const handleDragEnd = (
    draggingNode: any,
    dropNode: any,
    dropType: any,
    ev: any
) => {};

const btnViewAllFile = () => {
    breadTreeList.value = [];
    extractTreeData.value = [];
    treeHighlightCurrent.value = false;
    fileTypeID.value = "";
    treeFileTypeIDs.value = [];
    tmpFolderName.value = "";
    total.value = 0;
    tableData.value = [];
    previewSrcList.value = [];
    currentPage.value = 1;
    loadingDataMsg2.value = "数据载入中...";
    getFileList();
};

const btnUploadFile = () => {
    uploadDrawerFlag.value = true;
};
const checkUploadDrawerFlag = () => {
    uploadDrawerFlag.value = false;
};
const checkUpdateList = () => {
    total.value = 0;
    tableData.value = [];
    previewSrcList.value = [];
    loadingDataMsg2.value = "数据载入中...";
    getFileList();
};

const openFile = (item: any) => {
    if (item.file_path) {
        window.open(item.file_path, "_blank");
    }
};

const btnGetAllChooseFile = () => {
    const tmpFileID: any = [];
    const tmpFilePath: any = [];
    if (total.value > 0 && multipleSelection.value.length > 0) {
        tableData.value.forEach((item: any, index) => {
            multipleSelection.value.forEach((item2) => {
                if (item2 == item.id) {
                    tmpFileID.push(item.id);
                    tmpFilePath.push(item.file_path);
                }
            });
        });
    }
    emits(
        "btnChooseFile",
        tmpFileID,
        tmpFilePath,
        props.chooseFileLocation,
        props.chooseFieldID
    );
    multipleSelection.value = [];
};

const getFilePath = (id: any, path: any) => {
    emits(
        "btnChooseFile",
        id,
        path,
        props.chooseFileLocation,
        props.chooseFieldID
    );
};

onUnmounted(() => {});
</script>

<style lang="less" scoped>
.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
}
</style>
